<?php
namespace Admin\Controller;
use Admin\Common\Page;
class BagController extends BaseController
{
    /**
     * 书包列表
     */
    public function index()
    {
        $db = M();
        $key = I('get.keywords');
        $keyNick = I('get.child_name');
        if($key != ""){
            $map = " and b.bag_card like '%{$key}%'";
        }else{
            $map = "";
        }
        if($keyNick != ""){
            $map .= " and u.nickname like '%{$keyNick}%'";
        }
        $count = $db->table('bag as b,student as s,class,child_school as c,user as u')
            ->where("b.status=1 and b.stu_id=s.stu_id and s.class_id=class.id and  class.child_school_id=c.id and s.user_id=u.user_id".$map)
            ->field("b.bag_id,b.bag_card,class.class_name,c.name,u.nickname")
            ->count();
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $bagdata = $db->table('bag as b,student as s,class,child_school as c,user as u')
            ->where("b.status=1 and b.stu_id=s.stu_id and s.class_id=class.id and  class.child_school_id=c.id and s.user_id=u.user_id".$map)
            ->field("b.bag_id,b.bag_card,class.class_name,c.name,u.nickname,b.bag_name")
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('bagdata',$bagdata);
        $this->display();

    }
    /**
     * 创建书包
     */
    public function add(){
        $bag = M('bag');
        if(IS_POST){
            $data = I('post.');
//            var_dump($data);die;
            $res = $bag->data($data)->add();
            if($res){
                $this->success('创建成功',U('index'));

            }
            $this->error('创建失败');
        }else{
           // $bag_all  = M('bag')->select();
           // $this->assign('bag_data',$bag_all);
            $this->display();
        }
    }
    /**
     * 修改书包
     */
    public function edit(){
             $bag_id = I('get.bag_id');
            // $bag_data  = M('bag')->select();
             $bag_data = M('bag')->where("bag_id=$bag_id")->find();
             $this->assign('bag_data',$bag_data);
 //            $this->assign('data',$data);
             $this->display();


        }
    /**
     * do 修改书包
     */
    public function doedit(){
        $bag_id = I('get.bag_id');
        $data= I('post.');
      //  $data['childschool_id'] = I('post.childschool_id');
        $res = M('bag')->where("bag_id =$bag_id")->data($data)->save();
        if($res !==false){
            $this->success('修改成功',U('index'));

        }else{
            $this->error('修改失败');

        }



    }


    /**
     * 删除书包
     */
    public function del(){
        $bag_id=I('get.bag_id');
        // TODO  要先判断是不是空书包（还没实现）


        $res = M('bag')->where("bag_id=$bag_id")->delete();
        if($res >=1){
            $this->success('删除成功',U("index"));
        }else{
            $this->error('删除失败');
        }

    }



    /**
     * 锁定书包
     */
    public function lock(){
        $bag_id = I('post.bag_id');
        if($bag_id == ""){
            $this->error('参数错误');
        }
        $db = M();
        $bag = $db->table('bag')->where('bag_id='.$bag_id)->find();
        /*更改书包状态*/
        $key1 = $db->table('bag')->where('bag_id='.$bag_id)->save(array('status'=>2,'remark'=>I('post.remark')));
        /*更改学生状态 锁定:未来*/
        $key2 = $db->table('student')->where('stu_id='.$bag['stu_id'])->save(array('status'=>2));
        if($key1 && $key2){
            $db->commit();
            $this->success('锁定成功',U('index'));
        }else{
            $db->rollback();
            $this->error('锁定失败');
        }
    }





    /**
     * 查看班级下的学生
     */
    public function classstu(){
        $class_id = I('get.class_id');
        $classname =M('Class')->where("class_id=$class_id")->getField('class_name');
        $studata   = M('Student')->where("class_id = $class_id ")->select();
        $this->assign('classname',$classname);
        $this->assign('studata',$studata);
        $this->display();

    }





    /**
     * 图书列表
     */
    public function booklist()
    {
        $bag_id = I('get.bag_id');
        if($bag_id == ""){
            $this->error('参数错误');
        }
        $db = M();
        $count = $db->table('bag_book')->where('status=0 and bag_id='.$bag_id)->count();
        $Page = new  Page($count , C('page.size'));// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $this->assign('page' , $show);// 赋值分页输出
        $books = $db->table('bag as a,bag_book as b,book as c')
            ->where('a.bag_id=b.bag_id and b.status=0 and b.book_id=c.book_id and b.bag_id='.$bag_id)
            ->field('c.*,a.bag_name,b.id')
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('books',$books);
        $this->display();
    }

    /**
     * 替换绑定中的图书列表
     */
    public function replaceBook(){
        $db = M();
        if(IS_POST){
            $db->startTrans();
            /**
             * 注意要查询 本幼儿园中是否有替换的新书 不得重复
             * 1.查询本幼儿园是否有重复 图书
             */
            $bag_id=I('post.bag_id');
            $newBook = $db->table('book')->where("tm='".I('post.tm')."'")->find();
            if(!$newBook){
                $this->error("不存在条码为:".I('post.tm').'的图书');
            }
            $child_school_id = $db->table('bag as a,student as b,class')->where('b.class_id=class.id and a.stu_id=b.stu_id and a.bag_id='.I('post.bag_id'))->getField('class.child_school_id');
            $classIds =  $db->table('class')->where('status=0 and child_school_id='.$child_school_id)->getField('id',true);
            $classIds = trim(implode(',',$classIds),",");
            $bagIds = $db->table('student')->where("status=1 and class_id in(".$classIds.")")->getField('bag_id',true);
            $bagIds = trim(implode(',',$bagIds),",");
            $bookIds = $db->table('bag_book')->where('status=0 and bag_id in('.$bagIds.')')->getField('book_id',true);
            if(in_array($newBook['book_id'],$bookIds)){
                $this->error('当前替换图书在该幼儿园中已拥有');
            }
            /**
             * 2.将原书放入回收池 将旧书从借出转入缺失  将新替换的图书从库存转到借出一个
             */
            $data = $db->table('bag as a,student as b,class as c,child_school as d,card as e')
                ->where("a.bag_id={$bag_id} and a.stu_id=b.stu_id and b.class_id=c.id and c.child_school_id=d.id and b.card_id=e.card_id")
                ->field('a.bag_name,e.child_name,d.name,c.class_name')
                ->find();
            $key1 = $db->table('recover_book')->add(array(
                'book_id' => I('post.bag_book_id'),
                'user_name' => $data['child_name'],
                'class_name' => $data['class_name'],
                'school_name' => $data['name'],
                'bag_name' => $data['bag_name'],
                'remark' =>I('post.remark'),
                'created_at' => time()
            ));
            $link1 = D('book')->bookStatus(array(I('post.bag_book_id')),5);
            if($link1 == 400){
                $this->error('原书更改状态出错');
            }

            $link2 = D('book')->bookStatus(array(I('post.bag_book_id')),7);
            if($link2 == 400){
                $this->error('新书更改状态出错');
            }
            /**
             * 3.将原书的ID替换为新书的ID
             */
            $bagBook = $db->table('bag_book')->where('id='.I('post.bag_book_id'))->find();
            $bagBook['book_id'] = $newBook['book_id'];
            $key2 = $db->table('bag_book')->where('id='.$bagBook['id'])->save($bagBook);
            if($key1 && $key2){
                $link1->commit();
                $link2->commit();
                $db->commit();
                $this->success('替换成功',U('booklist',array('bag_id'=>$bag_id)));
            }else{
                $db->rollback();
                $this->error('替换失败');
            }

        }else{
            $bag_id = I('get.bag_id');
            $bag_book = I('get.bag_book');
            if($bag_id=="" || $bag_book==""){
                $this->error('参数错误');
            }
            $book = $db->table('bag_book as a,book as b')->field('a.*,b.sm,b.tm,b.book_id')->where('a.book_id=b.book_id and a.id='.$bag_book)->find();
            $this->assign('bag_id',$bag_id);
            $this->assign('book',$book);
            $this->display();

        }
    }

    /**
     * 解绑书包
     */
    public function untie(){
        $bag_id = I('get.bag_id');
        if($bag_id == ""){
            $this->error('参数错误');
        }
        $db = M();
        $db->startTrans();
        $stuId = $db->table('bag')->where('bag_id='.$bag_id)->getField('stu_id');
        /**
         * 1.将书包与学生之间断开关系
         */
        $key1 = $db->table('bag')->where('bag_id='.$bag_id)->save(array('stu_id'=>0,'status'=>0));
        $key2 = $db->table('student')->where('stu_id='.$stuId)->save(array('status'=>0,'bag_id'=>0));

        /**
         * 2.改变这些书的状态
         */
        $bookIds = $db->table('bag_book')->where('status=0 and bag_id='.$bag_id)->getField('book_id',true);
        $link = D('book')->bookStatus($bookIds,4);
        if($link == 400){
            $this->error('更改图书状态出错');
        }
        if($key2 && $key1){
            $db->commit();
            $link->commit();
            $this->success('解绑成功',U('index'));
        }else{
            $db->rollback();
            $this->error('解绑失败');
        }

    }


}

